//
//  SJCustomLayout.m
//  WSL
//
//  Created by CJ on 2017/10/8.
//  Copyright © 2017年 sanjuetech. All rights reserved.
//

// 待完善，现在只支持一个分组，没有footer的情况，以后有需求再完善

#import "SJCustomLayout.h"

NSString *const SJ_UICollectionElementKindSectionHeader = @"SJ_HeadView";
NSString *const SJ_UICollectionElementKindSectionFooter = @"SJ_FootView";

@interface SJCustomLayout ()

@property (strong, nonatomic) NSMutableDictionary *cellLayoutInfo; // 保存cell的布局
@property (strong, nonatomic) NSMutableDictionary *headLayoutInfo; // 保存头视图的布局
@property (strong, nonatomic) NSMutableDictionary *footLayoutInfo; // 保存尾视图的布局

@property (assign, nonatomic) CGFloat startY; // 记录开始的Y
@property (assign, nonatomic) CGFloat endY; // 记录最下面的Y
@property (assign, nonatomic) CGFloat endX; // 记录最下面的X

@end

@implementation SJCustomLayout

- (instancetype)init
{
    self = [super init];
    if (self) {
        
        self.startY = 0;
        self.endY = 0;
        self.endX = 0;
        self.cellLayoutInfo = [NSMutableDictionary dictionary];
        self.headLayoutInfo = [NSMutableDictionary dictionary];
        self.footLayoutInfo = [NSMutableDictionary dictionary];
    }
    return self;
}

- (void)prepareLayout
{
    [super prepareLayout];
    
    //重新布局需要清空
    [self.cellLayoutInfo removeAllObjects];
    [self.headLayoutInfo removeAllObjects];
    [self.footLayoutInfo removeAllObjects];
    self.endY = 0;
    self.endX = 0;
    self.startY = 0;
    
    //取有多少个section
    NSInteger sectionsCount = [self.collectionView numberOfSections];
    for (NSInteger section = 0; section < sectionsCount; section++) {
        
        //存储headerView属性
        NSIndexPath *supplementaryViewIndexPath = [NSIndexPath indexPathForRow:0 inSection:section];
        
        CGFloat height = 0;
        
        if ([self.delegate respondsToSelector:@selector(collectionView:layout:heightForHeaderInSection:)]) {
            
            height = [(id<SJCustomLayoutDelegate>)self.delegate collectionView:self.collectionView layout:self heightForHeaderInSection:section];
        }
        
        //头视图的高度不为0并且根据代理方法能取到对应的头视图的时候，添加对应头视图的布局对象
        if (height > 0 && [self.collectionView.dataSource respondsToSelector:@selector(collectionView: viewForSupplementaryElementOfKind: atIndexPath:)]) {
            
            UICollectionViewLayoutAttributes *attribute = [UICollectionViewLayoutAttributes layoutAttributesForSupplementaryViewOfKind:SJ_UICollectionElementKindSectionHeader withIndexPath:supplementaryViewIndexPath];
            //设置frame
            attribute.frame = CGRectMake(0, self.startY, self.collectionView.frame.size.width, height);
            //保存布局对象
            self.headLayoutInfo[supplementaryViewIndexPath] = attribute;
            //设置下个布局对象的开始Y值
            self.startY = self.startY + height;
            
        } else {
            //没有头视图的时候，也要设置section的第一排cell到顶部的距离
//            self.startY +=  xxx;
        }
        
        
        //计算cell的布局
        NSInteger rowsCount = [self.collectionView numberOfItemsInSection:section];
        //分别计算设置每个cell的布局对象
        for (NSInteger row = 0; row < rowsCount; row++) {
            
            NSIndexPath *cellIndexPath =[NSIndexPath indexPathForItem:row inSection:0];
            UICollectionViewLayoutAttributes *attribute = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:cellIndexPath];
            
            CGRect frame = [(id<SJCustomLayoutDelegate>)self.delegate collectionView:self.collectionView layout:self frameOfItemAtIndexPath:cellIndexPath];
            
            frame.origin.y += self.startY;
            
            //设置当前cell布局对象的frame
            attribute.frame = frame;
            
            //保留cell的布局对象
            self.cellLayoutInfo[cellIndexPath] = attribute;
            
            CGFloat bottom = frame.origin.y + frame.size.height;
            CGFloat right = frame.origin.x + frame.size.width;
            
            if (bottom > self.endY) {
                self.endY = bottom;
            }
            
            if (right > self.endX) {
                self.endX = right;
            }
        }
        
    }   
}

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
    NSMutableArray *allAttributes = [NSMutableArray array];
    
    //添加当前屏幕可见的cell的布局
    [self.cellLayoutInfo enumerateKeysAndObjectsUsingBlock:^(NSIndexPath *indexPath, UICollectionViewLayoutAttributes *attribute, BOOL *stop) {
        if (CGRectIntersectsRect(rect, attribute.frame)) {
            [allAttributes addObject:attribute];
        }
    }];
    
    //添加当前屏幕可见的头视图的布局
    [self.headLayoutInfo enumerateKeysAndObjectsUsingBlock:^(NSIndexPath *indexPath, UICollectionViewLayoutAttributes *attribute, BOOL *stop) {
        if (CGRectIntersectsRect(rect, attribute.frame)) {
            [allAttributes addObject:attribute];
        }
    }];
    
    
    return allAttributes;
}

//插入cell的时候系统会调用改方法
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewLayoutAttributes *attribute = self.cellLayoutInfo[indexPath];
    return attribute;
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForSupplementaryViewOfKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath {
    
    UICollectionViewLayoutAttributes *attribute = nil;
    if ([elementKind isEqualToString:SJ_UICollectionElementKindSectionHeader]) {
        attribute = self.headLayoutInfo[indexPath];
    } else if ([elementKind isEqualToString:SJ_UICollectionElementKindSectionFooter]){
        attribute = self.footLayoutInfo[indexPath];
    }
    return attribute;
}


- (CGSize)collectionViewContentSize {
    
    CGFloat bottom = SJMargin;
    
    if ([self.delegate respondsToSelector:@selector(bottomMarginInCollectionView:layout:)]) {
        
        bottom = [(id<SJCustomLayoutDelegate>)self.delegate bottomMarginInCollectionView:self.collectionView layout:self];
    }
    
//    return CGSizeMake(self.endX + SJMargin, self.endY + bottom);
    
    return CGSizeMake(SJScreenW, self.endY + bottom);
}


- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
    
    return NO;
}

@end
